#include "systime.h"
#include "hc_log.h"
#include "my_define.h"
#include "timeout_conf.h"
#include "radio/radio.h"
#include "event_queue/event_queue.h"

volatile u32 g_nSysTickCount = 0;

#define RF_PACKET_SIZE 20 /* Define the payload size here */

static u8 g_rxBuffer[RF_PACKET_SIZE + 1]; /* RF Rx buffer */
static u8 g_txBuffer[RF_PACKET_SIZE];     /* RF Tx buffer */

u32 g_nRecvCount = 0, g_nSendCount = 0;

// 使用32.8K的RCL作为系统时钟源
void App_ClkCfg(void)
{
    ///< 系统时钟源初始化
    stc_sysctrl_sysclk_source_init_t stcSysClkSrc = {0};
    stcSysClkSrc.u32SysClkSourceType = SYSCTRL_SYSCLK_SOURCE_TYPE_RCL;
    stcSysClkSrc.u32RCLState = SYSCTRL_RCL_TRIM_38p4KHz |
                               SYSCTRL_RCL_WAITCYCLE256;

    SYSCTRL_SysClkSrcInit(&stcSysClkSrc);
}
void Recv_Err(void)
{
    CMT2300A_GoStby();
    CMT2300A_ClearRxFifo();
    CMT2300A_ClearInterruptFlags();
    CMT2300A_GoSleep();
    CMT2300A_GoStby();
    CMT2300A_GoRx();
}
u8 Radio_Recv_FixedLen(u8 pBuf[], u8 len)
{
#ifdef ENABLE_ANTENNA_SWITCH
    if (CMT2300A_ReadGpio3()) // 300H只能有GPIO3做接收PKT_DONE中断
#else
    if (CMT2300A_ReadGpio2()) //  PKT_DONE
#endif
    {
        if (CMT2300A_MASK_PKT_OK_FLG & CMT2300A_ReadReg(CMT2300A_CUS_INT_FLAG)) /* 中断设置的时候PKT_DONE中断不代表一定收到一包数据，产生PKTD0NE的原因有四点具体请看芯片手册，所以此处在此查询是否Read PKT_OK flag */
        {
            CMT2300A_GoStby();
            CMT2300A_ReadFifo(pBuf, 1);
            if (pBuf[0] > 0 && pBuf[0] <= RF_PACKET_SIZE)
            {
                CMT2300A_ReadFifo(&pBuf[1], pBuf[0]);
                CMT2300A_ClearRxFifo();
                CMT2300A_ClearInterruptFlags();
                CMT2300A_GoSleep();
                return 1;
            }
            else
            {
                Recv_Err();
                return 0;
            }
        }
        else
        {
            Recv_Err();
            return 0;
        }
    }
    return 0;
}
void rf_receive()
{
    int i;
    static u32 delay = 30000000; // 超时 5 分钟

    // system_delay1ms(3000);
    if (Radio_Recv_FixedLen(g_rxBuffer, RF_PACKET_SIZE))
    {
        g_nRecvCount++;
        system_delay1ms(10);
        for (i = 0; i < RF_PACKET_SIZE + 1; i++)
            g_rxBuffer[i] = 0;
        CMT2300A_GoStby();
        CMT2300A_GoRx();
    }
    system_delay100us(1);
    delay--;
    if (delay == 0) // 超时时间到重新走一遍rx流程
    {

        delay = 30000000;
        CMT2300A_GoSleep();
        CMT2300A_GoStby();
#ifdef ENABLE_ANTENNA_SWITCH
        /* Config interrupt */
        CMT2300A_ConfigInterrupt(
            CMT2300A_INT_SEL_TX_DONE, /* Config INT1 */
            CMT2300A_INT_SEL_PKT_DONE /* 将INT2上的GPIO3设置为接收完成中断onfig INT2 */
        );
#endif
        /* Must clear FIFO after enable SPI to read or write the FIFO */
        CMT2300A_EnableReadFifo();
        CMT2300A_ClearInterruptFlags();
        CMT2300A_ClearRxFifo();
        CMT2300A_GoStby();
        if (CMT2300A_GoRx() == 0) // 状态切换失败,重新初始化RF，这里，需要注意如果有低功耗的场景，gosleep状态也要监控起来
        {
            RF_Init();
            CMT2300A_GoStby();
#ifdef ENABLE_ANTENNA_SWITCH
            /* Config interrupt */
            CMT2300A_ConfigInterrupt(
                CMT2300A_INT_SEL_TX_DONE, /* Config INT1 */
                CMT2300A_INT_SEL_PKT_DONE /* 将INT2上的GPIO3设置为接收完成中断onfig INT2 */
            );
#endif
            /* Must clear FIFO after enable SPI to read or write the FIFO */
            CMT2300A_EnableReadFifo();
            CMT2300A_ClearInterruptFlags();
            CMT2300A_ClearRxFifo();
            CMT2300A_GoRx();
        }
    }
}
// RX
int main(void)
{
    event_queue_init();
    App_ClkCfg();
    systime_init();
    SysTick_Config(3950);
RF_Init_Retry:
    RF_Init();
    if (FALSE == CMT2300A_IsExist())
    {
        while (1)
        {
        }
    }
    CMT2300A_GoStby();
    CMT2300A_EnableReadFifo();
    CMT2300A_ClearInterruptFlags();
    CMT2300A_ClearRxFifo();
    if (FALSE == CMT2300A_GoRx())
    {
        goto RF_Init_Retry;
    }
    while (1)
    {
        if (event_queue_is_empty() == false)
        {
            Event evt;
            if (event_queue_pop(&evt))
            {
                switch (evt.type)
                {
                case EVENT_DATA_READY:
                    rf_receive();
                    break;
                default:
                    break;
                }
            }
        }
        systime_enter_sleep();
    }
}
void SysTick_IRQHandler(void)
{
    g_nSysTickCount++;
}
void PortB_IRQHandler(void)
{
    if (CMT_GPIO2_GPIO_PIN | GPIO_ExtIrqStateGet(GPIOB, CMT_GPIO2_GPIO_PIN))
    {
        GPIO_ExtIrqStateClear(GPIOB, CMT_GPIO2_GPIO_PIN);
        event_queue_push_isr(EVENT_DATA_READY);
    }
}
#if 0
int main(void)
{
    App_ClkCfg();
    hc_log_init();
    systime_init();
    button_init();
    adc_driver_init();
    relay_ctrl_init();
    indicator_init();
    key_init();
    timeout_init();
    brightness_detect_init();
    brightness_sensor_mode_init();
    pir_sensor_sensitivity_init();
    pir_sensor_detect_init();
    mode_manage_init();

    while (1)
    {
        button_task();
        indicator_task();
        key_task();
        relay_ctrl_task();
        // 检测timeout时间挡位
        timeout_level_get_task();
        // 检测传感器模式挡位
        brightness_sensor_mode_check_task();
        brightness_detect_task();
        // 检测pir灵敏度挡位
        pir_sensor_sensitivity_task();
        // PIR检测
        pir_sensor_task();
        // 模式管理
        mode_manage_task();

        systime_enter_sleep();
    }
}
#endif
